package pers.zb.cloud.service.upms.util;



import pers.zb.cloud.service.upms.vo.RoleClientPermissionVo;

import java.util.ArrayList;
import java.util.List;

public class RoleClientPermissionTreeUtil {

    public static List<RoleClientPermissionVo> getPermissionTreeList(List<RoleClientPermissionVo> allTreeList){
        return getPermissionTreeList(allTreeList,null);
    }

    /**
     * 对于拥有子菜单的菜单，递归获取所有层级的子菜单数据
     */
    public static List<RoleClientPermissionVo> getPermissionTreeList(List<RoleClientPermissionVo> allMenuList, Long parentId){
        List<RoleClientPermissionVo> parentMenuList = new ArrayList<RoleClientPermissionVo>();
        //遍历所有菜单
        for (RoleClientPermissionVo menuVo : allMenuList) {
            if(null == parentId) {
                //先获取所有的父菜单
                if(-1L == menuVo.getPid() ) {
                    parentMenuList.add(menuVo);
                }
            }else {
                if( null != menuVo.getPid() && parentId.longValue() ==  menuVo.getPid().longValue()) {
                    parentMenuList.add(menuVo);
                }
            }
        }
        //从父菜单开始往下遍历，获取对应的子菜单
        for (RoleClientPermissionVo parentMenuVo : parentMenuList) {
            //获取该父菜单下面的第一层子菜单
            List<RoleClientPermissionVo> childMenuList = getMenuChildList(parentMenuVo.getId(),allMenuList);
            if(childMenuList.size() > 0) {
                parentMenuVo.setChildren(getMenuChildList(childMenuList,allMenuList));
            }

        }
        return parentMenuList;
    }

    /**
     * 递归方法，获取菜单的子菜单。依次往下递归，直至某个菜单下面没有子菜单为止
     *
     * @param childTreeList 某个父菜单下面的所有第一层子菜单
     * @param allTreeList 所有菜单数据
     * @return
     */
    private static List<RoleClientPermissionVo> getMenuChildList(List<RoleClientPermissionVo> childTreeList,List<RoleClientPermissionVo> allTreeList){
        for (RoleClientPermissionVo menuVo : childTreeList) {
            List<RoleClientPermissionVo> menuChildListTree = getMenuChildList(menuVo.getId(),allTreeList);
            if(menuChildListTree.size()>0) {
                menuVo.setChildren(getMenuChildList(menuChildListTree,allTreeList));
            }
        }
        return childTreeList;
    }

    /**
     * 获取父菜单对应的第一层子菜单
     *
     * @param id 父菜单的ID
     * @param allTreeList 所有菜单数据
     * @return
     */
    private static List<RoleClientPermissionVo> getMenuChildList(Long id,List<RoleClientPermissionVo> allTreeList){
        List<RoleClientPermissionVo> menuChildList = new ArrayList<RoleClientPermissionVo>();
        for (RoleClientPermissionVo menuVo : allTreeList) {
            if (null != menuVo.getPid() && menuVo.getPid().longValue() == id.longValue()) {
                menuChildList.add(menuVo);
            }
        }
        return menuChildList;
    }
}
